// --------------------------------------------------------------------------------------------------------------------
// <copyright file="StorageHelper.cs" company="">
//   
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Tests
{
    using Microsoft.WindowsAzure;
    using Microsoft.WindowsAzure.StorageClient;

    public static class StorageHelper
    {
        #region Public Methods and Operators

        public static bool ContainerExists(string storageAccount, string accessKey, string containerName)
        {
            // Create service client for credentialed access to the Blob service.
            var blobClient = new CloudBlobClient(
                BuildBlobServiceEndpoint(storageAccount), new StorageCredentialsAccountAndKey(storageAccount, accessKey));

            // Get a reference to a container, which may or may not exist.
            var container = blobClient.GetContainerReference(containerName);

            try
            {
                container.FetchAttributes();
                return true;
            }
            catch (StorageClientException sce)
            {
                if (sce.ErrorCode == StorageErrorCode.ContainerNotFound)
                {
                    return false;
                }

                throw;
            }
        }

        public static void DeleteBlob(string storageAccount, string accessKey, string blobUri)
        {
            // Create service client for credentialed access to the Blob service.
            var blobClient = new CloudBlobClient(
                BuildBlobServiceEndpoint(storageAccount), new StorageCredentialsAccountAndKey(storageAccount, accessKey));

            var blobRef = blobClient.GetBlobReference(blobUri);

            blobRef.Delete();
        }

        public static void DeleteContainer(string account, string key, string containerName)
        {
            // Create service client for credentialed access to the Blob service.
            var blobClient = new CloudBlobClient(BuildBlobServiceEndpoint(account), new StorageCredentialsAccountAndKey(account, key));

            // Get a reference to a container, which may or may not exist.
            var container = blobClient.GetContainerReference(containerName);

            container.Delete();
        }

        #endregion

        #region Methods

        private static string BuildBlobServiceEndpoint(string storageAccount)
        {
            return string.Format("https://{0}.blob.core.windows.net", storageAccount);
        }

        #endregion
    }
}
